import os
import logging
import wsgiref.handlers
import hashlib
import re
import random
#import modapplyaccount #werkt niet om de 1 of andere reden  dus
from google.appengine.api import mail
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
#from util.sessions import Session
from appengine_utilities.sessions import Session
from google.appengine.ext import db
from google.appengine.ext.webapp.util import run_wsgi_app



# zie http://www.daniweb.com/tutorials/tutorial238544.html en http://code.activestate.com/recipes/65215-e-mail-address-validation/

#

#een aantal global variables??

askedmember = 'nomember' #is dat wel verstandig??nee, denk het niet


# A Model for a User
class User(db.Model):
  account = db.StringProperty()
  password = db.StringProperty()
  emailaddress = db.StringProperty()
  name = db.StringProperty()
  timestamp = db.DateTimeProperty(auto_now_add=True)
  activated = db.BooleanProperty()
  activationhash = db.StringProperty()
  preferences = db.StringProperty()

# A helper for sending mail...

def doSendMail(tostr="wj.vandenbrink@gmail.com", subjectstr="bericht", bodystr="goed zo"):
  mail.send_mail(sender="wj.vandenbrink@gmail.com", 
    to=tostr, 
    subject=subjectstr, 
    body=bodystr)

	
# A helper to do the rendering and to add the necessary
# variables for the _base.htm template


def doRender(handler, tname = 'index.htm', values = { }):
  temp = os.path.join(
      os.path.dirname(__file__),
      'templates/' + tname)
  if not os.path.isfile(temp):
    return False

  # Make a copy of the dictionary and add the path and session
  newval = dict(values)
  newval['path'] = handler.request.path
  handler.session = Session()
  if 'username' in handler.session:
     newval['username'] = handler.session['username']

  outstr = template.render(temp, newval)
  handler.response.out.write(outstr)
  return True

class TestSessionHandler(webapp.RequestHandler):
  def get(self):
    self.session = Session()
    self.session['anoniem']= 'Onbekend!!! en toch bekend!!'
    plop = self.session['anoniem'] + ' ' # + self.session['loggedinuser']
    #iets = dir(appengine_utilities.sessions)
    #doRender(self, 'index2.html')
    doRender(self, 'index2.html', {'error' : 'get ' + ' : '} )
    
    #doRender(self, 'index2.html', {'error' : 'account ' + ' : ' + plop}


class Test2SessionHandler(webapp.RequestHandler):
  def get(self):
    self.session = Session()
    plop = self.session['anoniem']
    doRender(self, 'index2.html', {'error' : 'account ' + ' : ' + plop + ' from session'} )


class LoginAccountHandler(webapp.RequestHandler):
  def get(self):
    self.session = Session()
    referer1 = str(os.environ['HTTP_REFERER'])
    self.session['referer1'] = referer1
    doRender(self, 'stophoestLoginAccount.html', {'error' : ' : '} )
  def post(self):
    self.session = Session()
    referer2 = self.session['referer1']
    acct = self.request.get('account')
    pw = self.request.get('password')
    logging.info('Trying login of account='+acct)
    patternacct = r"[\'a-zA-Z0-9.\-]"
    patterpw = r"[a-zA-Z0-9_]"
    rexpacct = re.compile(patternacct)
    rexppw = re.compile(patterpw)
    if pw == '' or acct == '':
      doRender(
          self,
          'stophoestLoginAccount.html',
          {'account' : acct, 'password' : pw, 'error' : 'Please fill in all fields'} )
      return    
    if  (not rexpacct.match(acct)) or  (not rexppw.match(pw)):

      doRender(
          self,
          'stophoestLoginAccount.html',
          {'account' : acct, 'password' : pw, 'error' : 'faulty nickname or password'} )
      return
    que = db.Query(User).filter('account =',acct)
    results = que.fetch(limit=1)
    if len(results) == 0:
      doRender(
          self,
          'stophoestLoginAccount.html',
          {'account' : acct, 'password' : pw, 'error' : 'your account doesn\'t seem to exist!'} )
      return
      
    if len(results) > 0 :
      quer = User.gql("WHERE account = :1", acct)
      querdus = quer.get()
      if querdus.account == acct and querdus.activated==False:
        doRender(
          self,
          'stophoestLoginAccount.html',
          {'account' : acct, 'password' : pw, 'error' : 'your account exists but is not activated!'} )
        return

      if querdus.account == acct and querdus.activated==True:
        #now login this user...
        self.session['loggedinuser'] = acct
        inlgdusrname = str(querdus.name)
        inlgdusrid = str(querdus.key().id_or_name())
        self.session['inlgdusrid'] = inlgdusrid
        self.session['inlgdusrname'] = inlgdusrname
        identcode = self.session['loggedinuser'] + inlgdusrname
        #doRender(
          #self,
         # 'stophoestLoginAccount.html',
          #{'account' : acct, 'password' : pw, 'error' : 'your account exists!!' + str(identcode)} )
        #return
        doRender(
          self,
          'stophoestindex.html',
          {'inlgdusrname' : inlgdusrname} )
        self.redirect(referer2)
        return











      
      
      #doRender(
          #self,
          #'stophoestLoginAccount.html',
          #{'account' : acct, 'password' : pw, 'error' : 'your account exists!'} )
      #return
    
    #doRender(self, 'stophoestLoginAccount.html', {'error' : 'post ' + ' : ' + acct + ' ' + pw} )



class LogoutAccountHandler(webapp.RequestHandler):
  def get(self):
    self.session = Session()
    referer1 = str(os.environ['HTTP_REFERER'])
    self.session['referer1'] = referer1
    loggedinuser =  self.session['inlgdusrname']

    
    doRender(
        self,
        'stophoestLogoutAccount.html',
        {'inlgdusrname' : loggedinuser} )
    return
    


  def post(self):
    self.session = Session()
    referer2 = self.session['referer1']
    self.session.delete()
    self.session = Session()
    self.session['inlgdusrname']= 'Anonymous'
    inlgdusrname = self.session['inlgdusrname']
    self.session['inlgdusrid'] = 'Zeroo'
    self.session['loggedinuser'] = 'Nobody'
    #doRender(self,'stophoestindex.html',
          #{'inlgdusrname' : inlgdusrname} )
    #referer2
    self.redirect(referer2)
    return
    
    



class PreferencesHandler(webapp.RequestHandler):
  def get(self):
    self.session = Session()
    if (not self.session.has_key('inlgdusrname')) or (self.session['inlgdusrname'] == 'Anonymous'):
       self.session['inlgdusrname']='Anonymous'
       inlgdusrname = self.session['inlgdusrname']
       doRender(
           self,
           'stophoestPreferencesLginFirst.html',
             {'inlgdusrname' : inlgdusrname, 'error' : 'Please login first'} )
       return


      
    if self.session.has_key('inlgdusrname'):
      inlgdusrname = self.session['inlgdusrname']
    #inlgdusrname = 'kkk'
    doRender(
        self,
        'stophoestPreferences.html',
          {'inlgdusrname' : inlgdusrname, 'error' : 'Please fill in all fields'} )
    return
  
    


  def post(self):
    self.session = Session()
    if (not self.session.has_key('inlgdusrname')) or (self.session['inlgdusrname'] == 'Anonymous'):
       self.session['inlgdusrname']='Anonymous'
       inlgdusrname = self.session['inlgdusrname']
       doRender(
           self,
           'stophoestPreferencesLginFirst.html',
             {'inlgdusrname' : inlgdusrname, 'error' : 'Please login first'} )
       return
    else:
       error = ''
       inlgdusrname = self.session['inlgdusrname']
       digit1_year = self.request.get('digit1_year')
       digit2_year = self.request.get('digit2_year')
       digit3_year = self.request.get('digit3_year')
       digit4_year = self.request.get('digit4_year')
       stopyear = digit1_year + digit2_year + digit3_year + digit4_year
       if not stopyear.find('y') == -1:
         error += 'please fill in a year'
       elif int(stopyear) > 2010 and int(stopyear):
         error = 'do not take a year in the future please'
         
       stopmoment = 'y' + stopyear
       
       stopmonth = self.request.get('stopmonth')
       if stopmonth == '- Choose -':
         error += ', and choose a month of the year'
         
       if stopmonth == '1':
         stopmonthtxt = 'January'
       if stopmonth == '2':
         stopmonthtxt = 'Febuary'
       if stopmonth == '3':
         stopmonthtxt = 'March'
       if stopmonth == '4':
         stopmonthtxt = 'April'
       if stopmonth == '5':
         stopmonthtxt = 'May'
       if stopmonth == '6':
         stopmonthtxt = 'June'
       if stopmonth == '7':
         stopmonthtxt = 'July'
       if stopmonth == '8':
         stopmonthtxt = 'August'
       if stopmonth == '9':
         stopmonthtxt = 'September'
       if stopmonth == '10':
         stopmonthtxt = 'October'
       if stopmonth == '11':
         stopmonthtxt = 'November'
       if stopmonth == '12':
         stopmonthtxt = 'December'
         
       stopmoment += 'mo' + stopmonth
       
       digit1_day = self.request.get('digit1_day')
       digit2_day = self.request.get('digit2_day')
       if digit1_day == '0':
         stopday = digit2_day
       else:
         stopday = digit1_day + digit2_day
       if not stopday.find('d') == -1:
         error += '; choose a day of the month please'
       if  stopday.find('d') == -1 and int(stopday) >31:
         error += ', and a month does not have more than 31 days'

       stopmoment += 'd' + stopday
         
       digit1_hour = self.request.get('digit1_hour')
       digit2_hour = self.request.get('digit2_hour')
       if digit1_hour == '0':
         stophour = digit2_hour
       else:
         stophour = digit1_hour + digit2_hour
       if not stophour.find('h') == -1:
         error += '; choose a hour of the day please'
       if  stophour.find('h') == -1 and int(stophour) >24:
         error += ', and a day does not have more than 24 hours'
         
       stopmoment += 'h' + stophour
       
       digit1_minute = self.request.get('digit1_minute')
       digit2_minute = self.request.get('digit2_minute')
       if digit1_minute == '0':
         stopminute = digit2_minute
       else:
         stopminute = digit1_minute + digit2_minute
       if not stopminute.find('m') == -1:
         error += '; set the minutes in the hour please'
       if  stopminute.find('m') == -1 and int(stopminute) >60:
         error += ', and a hour does not have more than 60 minutes'

       stopmoment += 'mi' + stopminute


       
       digit1_second = self.request.get('digit1_second')
       digit2_second = self.request.get('digit2_second')
       if digit1_second == '0':
         stopsecond = digit2_second
       else:
         stopsecond = digit1_second + digit2_second
       if not stopsecond.find('s') == -1:
         error += '; set the seconds in the minute please'
       if  stopsecond.find('s') == -1 and int(stopsecond) >60:
         error += ', and a minute does not have more than 60 seconds'

       stopmoment += 's' + stopsecond

       if self.session.has_key('inlgdusrname') and not (self.session['inlgdusrname'] == 'Anonymous') :
          inlgdusrname = self.session['inlgdusrname']
          quer = User.gql("WHERE name = :1", inlgdusrname)
          querdus = quer.get()
          querdus.preferences = stopmoment
          querdus.put()
          geput= stopmoment
       
       doRender(
           self,
           'stophoestPreferences.html',
             {'inlgdusrname' : inlgdusrname, 'error' : error + 'Please fill in all fields' + digit1_year
              + digit2_year + digit3_year + digit4_year + '-' + stopmonth + geput, 'digit1_year' : digit1_year,
              'digit2_year' : digit2_year,
              'digit3_year' : digit3_year,
              'digit4_year' : digit4_year,
              'digit1_day' : digit1_day, 
              'digit2_day' : digit2_day,
              'digit1_hour' : digit1_hour,
              'digit2_hour' : digit2_hour,
              'digit1_minute' : digit1_minute,
              'digit2_minute' : digit2_minute,
              'digit1_second' : digit1_second,
              'digit2_second' : digit2_second, 'stopmonth' : stopmonth, 'stopmonthtxt' :  stopmonthtxt}  )
       return







    

class UserSpaceHandler(webapp.RequestHandler):



  
  def get(self):
    self.session = Session()
    #referer1 = str(os.environ['HTTP_REFERER'])
    #self.session['referer1'] = referer1
    loggedinuser =  self.session['inlgdusrname']
    askedspaceprefs = ''
    askedspacename = ''
    askedspaceaccount = ''
    renderpage = 'stophoestuserspace.html'
    askedspace= str(os.environ['PATH_INFO']) #hier moet gezocht worden naar een label en dan moet de database
    if not (askedspace.find('/stopped/') == -1):
      askedspacename = askedspace[9:]
      if len(askedspacename) > 0 and  askedspacename[-1] == '/':
        askedspacename = askedspacename[:-1]
        #askedspacename += 'ERZITEEN/'

      que1 = db.Query(User).filter('account =',askedspacename)
      results1 = que1.fetch(limit=1)
     # renderpage = 'stophoestuserspace.html'
      if len(results1) == 0:
        askedspacename += ': the page is not found'
        doRender(
          self,
          renderpage,
          {'loggedinuser' : askedspacename,
          'askedspaceprefs' : askedspaceprefs,
          'askedspacename' : askedspacename,
          'askedspaceaccount' : askedspaceaccount,
          'inlgdusrname' : loggedinuser})
        return




        
      if len(results1) > 0 :
        quer1 = User.gql("WHERE account = :1", askedspacename)
        querdus1 = quer1.get()
        if querdus1.account == askedspacename and querdus1.activated==False:
           askedspacename += ': the page is not active yet...'
           doRender(
             self,
             renderpage,
             {'loggedinuser' : askedspacename,
             'askedspaceprefs' : askedspaceprefs,
             'askedspacename' : askedspacename,
             'askedspaceaccount' : askedspaceaccount,
             'inlgdusrname' : loggedinuser})
           return







           
        if querdus1.account == askedspacename and querdus1.activated==True:
           askedspacename +=  ': this is his page' + querdus1.preferences
           renderpage = 'stoppedmember.html'
           askedspaceprefs = querdus1.preferences
           askedspacename = querdus1.name
           askedspaceaccount = querdus1.account
           doRender(
             self,
             renderpage,
             {'loggedinuser' : askedspacename,
             'askedspaceprefs' : askedspaceprefs,
             'askedspacename' : askedspacename,
             'askedspaceaccount' : askedspaceaccount,
             'inlgdusrname' : loggedinuser})
           return
           
           
           
           #doRender(
             #self,
             #'stoppedmember.html',
             #{'loggedinuser' : askedspacename})
           #return

    #doRender(
      #self,
      #renderpage,
      #{'loggedinuser' : askedspacename,
      # 'askedspaceprefs' : askedspaceprefs,
       #'askedspacename' : askedspacename,
      # 'askedspaceaccount' : askedspaceaccount})
  #  return









class ActivateacctHandler(webapp.RequestHandler):
  def get(self):
    activateacct = self.request.get('activateacct')
    #plopppp = str(activateacctr)
    #activateacctp = plopppp.replace('<', '')
    #activateacct = activateacctp.replace('>', '')
    actacct = self.request.get('acct')
    quer = User.gql("WHERE account = :1", actacct)
    querdus = quer.get()
    if querdus.account == actacct and querdus.activationhash==activateacct and querdus.activated==False:
       querdus.activated = True
       querdus.put()
       plop = 'and your account is now activated!'
    elif querdus.account == actacct and querdus.activationhash==activateacct and querdus.activated==True:
       #querdus.activated = True
       #querdus.put()
       plop = 'but this account has been activated before already!'
    elif querdus.account != actacct or querdus.activationhash!=activateacct:
       #querdus.activated = True
       #querdus.put()
       plop = 'but authorisation failed:something is wrong your activation link,no activation possible!'
    #plop = querdus.timestamp
    #activationstatus = querdus.activated
    #querdus.activated =  not activationstatus
    #querdus.put()
    doRender(self, 'stophoestActivationStatus.html', {'error' : 'account ' + actacct + ' : ' + str(plop)} )






class StoppedsmokingHandler(webapp.RequestHandler):

  def get(self):
    
    doRender(self, 'stoppedsmoking.html')




    

class ApplyAccountHandler(webapp.RequestHandler):

  def get(self):
    self.session = Session()
    referer1 = str(os.environ['HTTP_REFERER'])
    self.session['referer1'] = referer1
    
    doRender(self, 'stophoestApplyAccount.html', {'referer1' : referer1} )
  
  def post(self):
    self.session = Session()
    referer2 = self.session['referer1']
    loggedinuser =  self.session['inlgdusrname']
    
    name = self.request.get('name')
    acct = self.request.get('account')
    pw = self.request.get('password')
    email = self.request.get('emailaddress')
    logging.info('Adding account='+acct)
    patternemail = r"^[_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,4}$"
    patternname = r"[\'a-zA-Z .\-]"
    patternacct = r"[\'a-zA-Z0-9.\-]"
    patterpw = r"[a-zA-Z0-9_]"
    mail = 'l'
    rexpmail = re.compile(patternemail)
    rexpname = re.compile(patternname)
    rexpacct = re.compile(patternacct)
    rexppw = re.compile(patterpw)
    if pw == '' or acct == '' or name == '' or email == '':
      doRender(
          self,
          'stophoestApplyAccount.html',
          {'name' : name, 'account' : acct, 'password' : pw,'emailaddress' : email, 'error' : 'Please fill in all fields'} )
      return


    if  not rexpname.match(name):

      doRender(
          self,
          'stophoestApplyAccount.html',
          {'name' : name, 'account' : acct, 'password' : pw,'emailaddress' : email, 'error' : 'faulty name'} )
      return
    if  not rexpacct.match(acct):

      doRender(
          self,
          'stophoestApplyAccount.html',
          {'name' : name, 'account' : acct, 'password' : pw,'emailaddress' : email, 'error' : 'faulty nickname'} )
      return

	# Check emailaddress
    if  not rexpmail.match(email):
    #if re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", email) != None:

      doRender(
          self,
          'stophoestApplyAccount.html',
          {'name' : name, 'account' : acct, 'password' : pw,'emailaddress' : email, 'error' : 'faulty emailaddress'} )
      return
    if  not rexppw.match(pw):

      doRender(
          self,
          'stophoestApplyAccount.html',
          {'name' : name, 'account' : acct, 'password' : pw,'emailaddress' : email, 'error' : 'faulty password'} )
      return


		
	

    # Check if the user already exists
    que = db.Query(User).filter('account =',acct)
    results = que.fetch(limit=1)

    if len(results) > 0 :
      doRender(
          self,
          'stophoestApplyAccount.html',
          {'name' : name, 'account' : acct, 'password' : pw,'emailaddress' : email, 'error' : 'Account already exists!'} )
      return

    # Create the User object and log the user in
    # First, make activationhash to email to the emailaddress voor account activation
    extraseed = random.sample(['a', 'b', 'c', 'd', 'e', 'f'], 5)
    seed = ''.join(extraseed)
    activationcode = hashlib.sha1(seed + email).hexdigest()
    #activationurl = "http://localhost:8080/activateacct/" + acct + ".htm" + "?acct=" + acct + "&activateacct=" + activationcode
    activationurl = "http://worldworldorg.appspot.com/activateacct/" + acct + ".htm" + "?acct=" + acct + "&activateacct=" + activationcode
    # Now send activationcode to emailaddress
    
    doSendMail(email, "activation account", activationurl)
    newuser = User(name=name, account=acct, password=pw, emailaddress=email, activated=False, activationhash=activationcode);
    pkey = newuser.put();

    #self.session['username'] = acct
    #self.session['userkey'] = pkey
    doRender(self,'stophoestThanks.html',{'referer2' : referer2, 'inlgdusrname' : loggedinuser})






#class TestHandler(webapp.RequestHandler):
  #def get(self):
    # print wsgiref.util.request_uri(self)???
    # print  os.environ['SERVER_NAME']  + os.environ['SERVER_PORT'] + os.environ['QUERY_STRING'] 
    # helaas werken er veel van de invironvariabelen niet hier: moet url hard-coden helaas

    
class MainHandler(webapp.RequestHandler):

  def get(self):
    self.session = Session()
    henk = str(os.environ['PATH_INFO'])
    inlgdusrname = 'Anonymous'
    inlgdusrid = 'Zeroo'
    loggedinuser = 'Nobody'
    if self.session.has_key('inlgdusrname'):
      inlgdusrname = self.session['inlgdusrname']
      inlgdusrid = self.session['inlgdusrid']
      loggedinuser = self.session['loggedinuser']
    else:
      self.session['inlgdusrname']= 'Anonymous'
      self.session['inlgdusrid'] = 'Zeroo'
      self.session['loggedinuser'] = 'Nobody'
    #self.session['inlgdusrname']= 'Anonymous'
    if doRender(self,self.request.path) :
      return
    doRender(self,'stophoestindex.html',
          {'inlgdusrname' : inlgdusrname, 'loggedinuser' :  loggedinuser} )

def main():
  
  application = webapp.WSGIApplication([
     #('/login', LoginHandler),
     ('/loginaccount', LoginAccountHandler),
     #(gebruikersruimte, UserSpaceHandler),#hier moet de handler komen voor het weergeven van gebruikergegevens
     ('/logoutaccount', LogoutAccountHandler),
     #('/apply', ApplyHandler),
     ('/applyaccount', ApplyAccountHandler),
     ('/activateacct/.*', ActivateacctHandler),
     ('/preferences', PreferencesHandler),
     #('/members', MembersHandler),
     #('/chat', ChatHandler),
     #('/messages', MessagesHandler),
     #('/logout', LogoutHandler),
     #('/stoppedsmoking', StoppedsmokingHandler),
     #('/mail', MailHandler),
     ('/test.htm', TestSessionHandler),
     ('/stoppedmembers', StoppedMembersHandler), 
     ('/test2.htm', Test2SessionHandler),
     ('/stopped/.*', UserSpaceHandler),
     ('/.*', MainHandler)],
     debug=True)
  wsgiref.handlers.CGIHandler().run(application)
  #run_wsgi_app(applications['localhost:8080'])
  


if __name__ == '__main__':
  main()
